/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.service;

import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.storage.common.MemberType;
import com.jeesite.modules.storage.dao.*;
import com.jeesite.modules.storage.entity.*;
import com.jeesite.modules.storage.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 商品Service
 */
@Service
@Transactional(readOnly = true)
public class GoodsService extends CrudService<GoodsDao, Goods> {

    @Autowired
    private GoodsSpecDao goodsSpecDao;

    @Autowired
    private GoodsSpecService goodsSpecService;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private MemberDao memberDao;

    /**
     * 获取单条数据
     *
     * @param goods
     * @return
     */
    @Override
    public Goods get(Goods goods) {
        Goods entity = super.get(goods);
        if (entity != null) {
            entity.setBrand(brandDao.get(new Brand(entity.getBrandId())));
            entity.setCate(categoryDao.get(new Category(entity.getCateId())));
            GoodsSpec goodsSpec = new GoodsSpec();
            goodsSpec.setGoodsId(entity.getId());
            entity.setGoodsSpecList(goodsSpecDao.findList(goodsSpec));
        }
        return entity;
    }

    /**
     * 查询分页数据
     *
     * @param goods 查询条件
     * @return
     */
    @Override
    public Page<Goods> findPage(Goods goods) {
        Page<Goods> goodsPage= super.findPage(goods);
        List<Goods> goodsList = goodsPage.getList();
        for (Goods item : goodsList){
            item.setBrand(brandDao.get(new Brand(item.getBrandId())));
            item.setCate(categoryDao.get(new Category(item.getCateId())));
            item.setGoodsSpecList(goodsSpecDao.findListByGoodsId(item.getId()));
        }
        return goodsPage;
    }

    /*
     * 获取分享图
     * @param memberId 会员Id
     * @param transActivityId 转发Id
     * @param activityId 活动Id
     * @param goodsId 商品Id
     * @param method 方式【单图、多图】
     * @param isBuy 是否购买
     * @return 分享图
     */
    public String getSharePic(String transActivityId,String goodsId,Integer stockNum,String method, Boolean isBuy){
        Map goodsMap = getSharePicById(goodsId);
        String code = String.valueOf(goodsMap.get("code"));
        String name = String.valueOf(goodsMap.get("name"));
        Double sourcePrice = Double.parseDouble(String.valueOf(goodsMap.get("price")));
        Double salePrice = WebUtil.getSalePrice(MemberType.VIP_TYPE,goodsMap);
        String stepUrl = WebUtil.getWebResourceUrl("/img/step.png");

        String thumbnail = String.valueOf(goodsMap.get("thumbnail"));

        if(method.equals("单图") && !isBuy){
            Map<String,String> map = new HashMap<>();

            map.put("{{code}}",code);
            map.put("{{name}}",name);
            map.put("{{sourcePrice}}",String.valueOf(sourcePrice));
            map.put("{{salePrice}}",String.valueOf(salePrice));
            map.put("{{stockNum}}",String.valueOf(stockNum));
            map.put("{{step}}",stepUrl);

            String shareThumbnail = thumbnail;// "/userfiles/goods/thumbnail/" + UUID.randomUUID() + ".png";
//            WebUtil.thumbnails(WebUtil.getRootPath(thumbnail),WebUtil.getRootPath(shareThumbnail));

            map.put("{{thumbnail}}",WebUtil.getWebUrl(shareThumbnail));
            String sharePic = "/userfiles/goods/share/" + UUID.randomUUID() + ".png";
            WebUtil.html2Image(WebUtil.getHtmlPath("1.html"),map, WebUtil.getRootPath(sharePic));

            return sharePic;
        }

        String picture = String.valueOf(goodsMap.get("picture"));
        String[] pictures = StringUtils.isNotBlank(picture) ? picture.split("\\|") : null;

        if(method.equals("多图") && !isBuy){
            Map<String,String> map = new HashMap<>();

            map.put("{{code}}",code);
            map.put("{{name}}",name);
            map.put("{{sourcePrice}}",String.valueOf(sourcePrice));
            map.put("{{salePrice}}",String.valueOf(salePrice));
            map.put("{{stockNum}}",String.valueOf(stockNum));
            map.put("{{step}}",stepUrl);

            for (Integer i = 0; i < 4 ; i ++){
                String sharePic = pictures[i];// "/userfiles/goods/picture/" + UUID.randomUUID() + ".png";
//                WebUtil.thumbnails(WebUtil.getRootPath(pictures[i]),WebUtil.getRootPath(sharePic));
                map.put("{{pic" + (i + 1) + "}}",WebUtil.getWebUrl(sharePic));
            }

            String sharePic = "/userfiles/goods/share/" + UUID.randomUUID() + ".png";
            WebUtil.html2Image(WebUtil.getHtmlPath("3.html"),map,WebUtil.getRootPath(sharePic));

            return  sharePic;
        }

        String qrCodeName = "/goods/qrcode/" + UUID.randomUUID() + ".png";
        String qrCodePath = WebUtil.getUserFilesPath(qrCodeName);
        String qrCodeUrl = WebUtil.getWebUserFilesUrl(qrCodeName);
        if(isBuy){
            WebUtil.buildQRCode(104,104,WebUtil.getH5FullUrl("/brand/detail?transActivityId=" + transActivityId),qrCodePath);
        }

        if(method.equals("单图") && isBuy){
            Map<String,String> map = new HashMap<>();

            map.put("{{code}}",code);
            map.put("{{name}}",name);
            map.put("{{sourcePrice}}",String.valueOf(sourcePrice));
            map.put("{{salePrice}}",String.valueOf(salePrice));
            map.put("{{stockNum}}",String.valueOf(stockNum));
            map.put("{{step}}",stepUrl);

            String shareThumbnail = thumbnail;// "/userfiles/goods/thumbnail/" + UUID.randomUUID() + ".png";
//            WebUtil.thumbnails(WebUtil.getRootPath(thumbnail),WebUtil.getRootPath(shareThumbnail));

            map.put("{{thumbnail}}",WebUtil.getWebUrl(shareThumbnail));

            map.put("{{qrCode}}",qrCodeUrl);

            String sharePic = "/userfiles/goods/share/" + UUID.randomUUID() + ".png";
            WebUtil.html2Image(WebUtil.getHtmlPath("2.html"),map,WebUtil.getRootPath(sharePic));

            return  sharePic;
        }

        if(method.equals("多图") && isBuy){
            Map<String,String> map = new HashMap<>();

            map.put("{{code}}",code);
            map.put("{{name}}",name);
            map.put("{{sourcePrice}}",String.valueOf(sourcePrice));
            map.put("{{salePrice}}",String.valueOf(salePrice));
            map.put("{{stockNum}}",String.valueOf(stockNum));
            map.put("{{step}}",stepUrl);

            for (Integer i = 0; i < 4 ; i ++){
                String sharePic = pictures[i];// "/userfiles/goods/picture/" + UUID.randomUUID() + ".png";
//                WebUtil.thumbnails(WebUtil.getRootPath(pictures[i]),WebUtil.getRootPath(sharePic));
                map.put("{{pic" + (i + 1) + "}}",WebUtil.getWebUrl(sharePic));
            }

            map.put("{{qrCode}}",qrCodeUrl);

            String sharePic = "/userfiles/goods/share/" + UUID.randomUUID() + ".png";
            WebUtil.html2Image(WebUtil.getHtmlPath("4.html"),map,WebUtil.getRootPath(sharePic));

            return sharePic;
        }

        return "";
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param goods
     */
    @Override
    @Transactional(readOnly = false)
    public void save(Goods goods) {
        Double price = 0d;
        Double memberPrice = 0d;
        Double vipPrice = 0d;
        Double agentPrice = 0d;

        for (GoodsSpec goodsSpec : goods.getGoodsSpecList()) {
            if(GoodsSpec.STATUS_DELETE.equals(goodsSpec.getStatus())){
                continue;
            }
            if(price == 0 ||  goodsSpec.getPrice() > price){
                price = goodsSpec.getPrice();
            }
            if(memberPrice == 0 || goodsSpec.getMemberPrice() < memberPrice){
                memberPrice = goodsSpec.getMemberPrice();
            }
            if(vipPrice == 0 || goodsSpec.getVipPrice() < vipPrice){
                vipPrice = goodsSpec.getVipPrice();
            }
            if(agentPrice == 0 || goodsSpec.getAgentPrice() > agentPrice){
                agentPrice = goodsSpec.getAgentPrice();
            }
        }

        goods.setPrice(price);
        goods.setMemberPrice(memberPrice);
        goods.setVipPrice(vipPrice);
        goods.setAgentPrice(agentPrice);

        if(StringUtils.isNotBlank(goods.getThumbnail())){
            String thumbnail = goods.getThumbnail();//"/userfiles/goods/thumbnail/" + UUID.randomUUID() + "." + WebUtil.getExtension(goods.getThumbnail());
//            WebUtil.thumbnails(WebUtil.getRootPath(goods.getThumbnail()),WebUtil.getRootPath(thumbnail));
            goods.setThumbnail(thumbnail);
        }

        if(StringUtils.isNotBlank(goods.getPicture())){
            String[] pictures = goods.getPicture().split("\\|");
            for (Integer i = 0 ; i < pictures.length ; i ++){
                String picture = pictures[i];//"/userfiles/goods/picture/" + UUID.randomUUID() + "." + WebUtil.getExtension(pictures[i]);
//                WebUtil.thumbnails(WebUtil.getRootPath(pictures[i]),WebUtil.getRootPath(picture));
                pictures[i] = picture;
            }
            goods.setPicture(String.join("|",pictures));
        }

        super.save(goods);

        //商品规格表
        GoodsSpec searchGoodsSpec = new GoodsSpec();
        searchGoodsSpec.setGoodsId(goods.getId());
        List<GoodsSpec> dbGoodsSpecList = goodsSpecDao.findList(searchGoodsSpec);
        for (GoodsSpec goodsSpec : dbGoodsSpecList){
            goodsSpecDao.phyDelete(goodsSpec);
        }

        // 保存 Goods子表
        List<GoodsSpec> goodsSpecList = goods.getGoodsSpecList();
        for (Integer i = 0; i < goodsSpecList.size(); i++) {
            GoodsSpec goodsSpec = goodsSpecList.get(i);
            if(GoodsSpec.STATUS_DELETE.equals(goodsSpec.getStatus())){
                continue;
            }
            goodsSpec.setSort(i + 1);
            goodsSpec.setBrandId(goods.getBrandId());
            goodsSpec.setCateId(goods.getCateId());
            goodsSpec.setGoodsId(goods.getId());
            goodsSpecDao.insert(goodsSpec);
        }
    }

    /**
     * 更新状态
     *
     * @param goods
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(Goods goods) {
        super.updateStatus(goods);
    }

    /**
     * 删除数据
     *
     * @param goods
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(Goods goods) {
        super.delete(goods);
        GoodsSpec goodsSpec = new GoodsSpec();
        goodsSpec.setGoodsId(goods.getId());
        goodsSpecDao.deleteByEntity(goodsSpec);
    }

    /**
     * 获取商品详情
     * @param type 会员类型
     * @param map 数据库数据
     * @return 商品详情
     */
    private Map getMap(String type, Map map){
        String goodsId = String.valueOf(map.get("goodsId"));
        String activityId = String.valueOf(map.get("activityId"));
        String picture = String.valueOf(map.get("picture"));
        map.put("pictures",StringUtils.isBlank(picture) ? new ArrayList<String>() : picture.split("\\|"));
        map.put("sourcePrice",map.get("price"));
        map.put("salePrice",WebUtil.getSalePrice(type,map));
        map.put("specList",goodsSpecService.getActivityListByGoodsId(type, activityId,goodsId));
        return  map;
    }

    /**
     * 获取限时爆款商品列表
     * @param memberId 会员Id
     * @param startTime 开始时间
     * @param size 每页数量
     * @param size 每页数量
     * @param page 页码
     * @return 限时爆款商品列表
     */
    public List<Map> getLimitedListByStartTime(String memberId, Date startTime,Integer size, Integer page){
        String type = memberDao.findTypeById(memberId);
        if(StringUtils.isBlank(type)){
            return  new ArrayList<>();
        }
        List<Map> maps = new ArrayList<>();
        List<Map> goodsList = dao.findLimitedListByStartTime(startTime,size * (page - 1) , size);
        for (Map map : goodsList){
            maps.add(getMap(type,map));
        }
        return maps;
    }

    /**
     * 品牌商品
     * @param memberId 会员Id
     * @param activityId 活动Id
     * @param transActivityId 转发Id
     * @param sort 排序
     * @param direction 方向
     * @param size 每页数量
     * @param page 页码
     * @return 品牌商品
     */
    public List<Map> getBrandList(String memberId, String activityId,String transActivityId, String sort, String direction, Integer size, Integer page){
        String type = memberDao.findTypeById(memberId);
        if(StringUtils.isBlank(type)){
            return  new ArrayList<>();
        }
        List<Map> maps = new ArrayList<>();
        List<Map> goodsList = dao.findBrandList(activityId, transActivityId,sort,direction,size * (page - 1) , size);
        for (Map map : goodsList){
            maps.add(getMap(type,map));
        }
        return maps;
    }

    /**
     * 获取活动商品列表
     * @param memberId 会员Id
     * @param activityId 活动Id
     * @return 活动商品列表
     */
    public List<Map> getListByActivityId(String memberId, String activityId){
        String type = memberDao.findTypeById(memberId);
        if(StringUtils.isBlank(type)){
            return  new ArrayList<>();
        }
        List<Map> maps = new ArrayList<>();
        List<Map> goodsList = dao.findListByActivityId(activityId);
        for (Map map : goodsList){
            maps.add(getMap(type,map));
        }
        return maps;
    }

    /**
     * 获取更多素材【Id】
     * @param memberId 会员Id
     * @param goodsId 商品Id
     * @return 更多素材
     */
    public Map getMoreById(String memberId, String goodsId){
        String type = memberDao.findTypeById(memberId);
        if(StringUtils.isBlank(type)){
            return new HashMap();
        }
        List<Map> maps = dao.findMoreById(goodsId);
       return maps.size() > 0 ? getMap(type,maps.get(0)) : new HashMap();
    }


    /**
     * 获取Id【编码】
     * @param code 编码
     * @return 查找Id
     */
   public String getIdByCode(String code){
       return dao.findIdByCode(code);
   }

    /**
     * 获取品牌Id【Id】
     * @param goodsId 商品Id
     * @return 品牌Id
     */
    public  String getBrandIdById(String goodsId){
        return dao.findBrandIdById(goodsId);
    }

    /**
     * 获取分类Id【Id】
     * @param goodsId 商品Id
     * @return 分类Id
     */
    public String getCateIdById(String goodsId){
        return dao.findCateIdById(goodsId);
    }

    /*
     * 获取分享图
     * @param goodsId 商品Id
     * @return 分享图
     */
    public Map getSharePicById(String goodsId){
        return dao.findSharePicById(goodsId);
    }

    /**
     * 查询分享【Id】
     * @param goodsId 商品Id
     * @return 分享
     */
    public Map getShareById(String goodsId){
        return dao.findShareById(goodsId);
    }

    /**
     * 获取价格
     * @param goodsSpecId 商品规格Id
     * @return 价格
     */
    public Map getPrices(String goodsSpecId){
        return dao.findPrices(goodsSpecId);
    }
}
